package com.demoworld;

import java.beans.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Description
 * <p>
 * </p>
 * DATE 2018/5/15.
 *
 * @author liwei5.
 */
public class Bean {
    private int x;
    private String str;
    private boolean isFlag = true;

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public String getStr() {
        return str;
    }

    public void setStr(String str) {
        this.str = str;
    }

    public boolean isFlag() {
        return isFlag;
    }

    public void setFlag(boolean flag) {
        isFlag = flag;
    }

    private static Object getProperty(Bean bean, String propertyName)
            throws IntrospectionException, IllegalAccessException,
            InvocationTargetException {
        Object retVal = null;
        //BeanInfo 就能够描述Bean.class的所有细节
        BeanInfo beanBeanInfo = Introspector.getBeanInfo(bean.getClass());

        PropertyDescriptor[] pds = beanBeanInfo.getPropertyDescriptors();

        for (PropertyDescriptor pd : pds) {
            if (pd.getName().equals(propertyName)) {
                Method methodGet = pd.getReadMethod();
                retVal = methodGet.invoke(bean, null);
                break;
            }
        }
        return retVal;
    }

    public static void main(String[] args) throws IllegalAccessException, IntrospectionException, InvocationTargetException {
        Bean bean = new Bean();
        String propertyName = "flag";
        Object retVal = getProperty(bean, propertyName);
        System.out.println(retVal);
    }
}
